package com.alianzamedica.models;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;

import org.objectsearch.sqlsearch.ObjectSearch;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Prescription;
import com.alianzamedica.businessobject.PrescriptionDetail;
import com.alianzamedica.connection.ConnectionImpl;
import com.alianzamedica.tools.Enviroment;

/**
 * @author Carlos
 * 
 */
public class PrescriptionSellingModel {

	/**
	 * obtiene los detalles del codigo de barra.
	 * 
	 * @param prescription
	 *            prescripcion.
	 * @param barCode
	 *            codigo de barras.
	 * @return detalle de la prescripcion.
	 * @throws Exception
	 *             si ocurre error.
	 */
	public PrescriptionDetail getDetailFromBarCode(Prescription prescription,
			String barCode) throws Exception {
		// int id = prescription.getId();
		String sql = "select DRUG_ID from drug WHERE DRUG_BARCODE = ?";
		ConnectionImpl impl = new ConnectionImpl();
		PreparedStatement psmt = null;
		ResultSet rs = null;
		PrescriptionDetail detail = null;
		try {
			impl.open();
			Connection con = impl.getConnection();
			psmt = con.prepareStatement(sql);
			psmt.setString(1, barCode);
			rs = psmt.executeQuery();
			while (rs.next()) {
				int drugId = rs.getInt("DRUG_ID");
				detail = this.getDetail(prescription, drugId);
			}
		} finally {
			try {
				rs.close();
			} catch (Exception e) {
			}
			try {
				psmt.close();
			} catch (Exception e) {
			}
			try {
				impl.close();
			} catch (Exception e) {
			}
		}
		return detail;
	}

	@SuppressWarnings("unchecked")
	private PrescriptionDetail getDetail(Prescription prescription, int drugId)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		PrescriptionDetail pd = new PrescriptionDetail();
		pd.setPrescriptionId(prescription.getId());
		pd.setDrugId(drugId);
		Iterator<PrescriptionDetail> iterator = search.searchObjects(pd)
				.iterator();
		PrescriptionDetail prescriptionDetail = null;
		while (iterator.hasNext()) {
			prescriptionDetail = (PrescriptionDetail) iterator.next();
		}
		return prescriptionDetail;
	}

	/**
	 * @param list
	 * @throws Exception
	 */
	public void updateSellDetails(ArrayList<PrescriptionDetail> list)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		int size = list.size();
		for (int i = 0; i < size; i++) {
			search.addBatchObject(list.get(i));
		}
		search.executeBatchUpdate();
	}

}
